package org.elanfox.intellicommunity.msg.server.base;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 频道注册器
 *
 * @author allan
 * @version 1.0.0
 * @date 2019/12/12
 */
@Slf4j
public class MsgChannelRegister {
    public static final Map<String, Channel> CHANNELS = new ConcurrentHashMap<>();

    /**
     * 添加一个对应channel
     *
     * @param channel
     * @param id
     */
    public static void register(String id, Channel channel) {
        log.info("channel registered----id：" + id);
        CHANNELS.put(id, channel);
    }

    /**
     * 移出一个channel
     *
     * @param channel
     */
    public static void remove(Channel channel) {
        String removeId = null;
        for (Map.Entry<String, Channel> channelEntry : CHANNELS.entrySet()) {
            if (channel.id().equals(channelEntry.getValue().id())) {
                removeId = channelEntry.getKey();
            }
        }
        if (removeId != null) {
            CHANNELS.remove(removeId);
        }
    }

    /**
     * 得到一个channel
     *
     * @param id
     * @return
     */
    public static Channel get(String id) {
        return CHANNELS.get(id);
    }

    public static boolean isExist(String id) {
        return CHANNELS.containsKey(id);
    }
}
